package login.config;

import login.service.MyAuthenticationService;
import login.service.MyDetailsService;
import login.service.MyLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyDetailsService myDetailsService;
    @Autowired
    private PersistentTokenRepository persistentTokenRepository;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private MyAuthenticationService myAuthenticationService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/setUser").antMatchers("/user").antMatchers("/loginU");
        super.configure(web);
    }

    //Spring Security配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//         自定义表单登录
        http.formLogin()
                .loginPage("/loginU")
//                .loginProcessingUrl("/loginU")
//                .successForwardUrl("/details")
                .usernameParameter("name")
                .passwordParameter("password")
                .loginProcessingUrl("/loginU")
                .successHandler(myAuthenticationService)
                .failureHandler(myAuthenticationService);

//                .and().rememberMe()
//                .tokenValiditySeconds(120960000)
//                .and().authorizeRequests().antMatchers("/sendyzm").permitAll()
//                .anyRequest().authenticated();


        // 需要认证的资源
        http.authorizeRequests()
                .antMatchers("/loginUser").permitAll() //登录页不需要认证
                .antMatchers("/setUser").permitAll()

                ; //其余所有请求都需要认证

        // 退出登录配置
        http.logout()
                .logoutUrl("/logout") // 退出登录路径
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                .clearAuthentication(true) //清除认证状态，默认为true
                .invalidateHttpSession(true); // 销毁HttpSession对象，默认为true
//
// 记住我配置
        http.rememberMe()
                .userDetailsService(userDetailsService)//登 录逻辑交给哪个对象
                .tokenRepository(persistentTokenRepository)//持久 层对象
                .tokenValiditySeconds(60); //保存时间，单位：秒

        http.authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .and()
                .rememberMe()
                .and()
                .csrf()
                .disable();

        http.cors();

    }
        //关闭csrf防护
//        http.csrf().disable();

//    public CorsConfigurationSource corsConfigurationSource(){
//        CorsConfiguration corsConfiguration = new CorsConfiguration();
//        //允许跨域的站点
//        corsConfiguration.addAllowedOrigin("*");
//        //允许跨域的方法
//        corsConfiguration.addAllowedMethod("*");
//        //允许跨域的请求头
//        corsConfiguration.addAllowedHeader("*");
//        //对所有url都生效
//
//        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
//
//        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
//        return urlBasedCorsConfigurationSource;
//    }


//
//
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        // 静态资源放行
//        web.ignoring().antMatchers("/css/**");
//    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
